<!-- 这个组件在未来会被废弃，改为D@\src\views\order\detail\components\part\CheckModal.vue -->
<template>
  <h-drawer
    v-model="visible"
    :width="1200"
    unit="px"
    :loading="saveLoading || getDetailLoading || getListDetailLoading || getWarehouseLoading"
    @close="onCancel"
  >
    <template #title>
      <div class="drawer_title_container">
        <span>{{ props.modalType ? '审核配件' : '编辑配件' }}</span>
        <HStatus type="warning" :height="20">待审核</HStatus>
      </div>
    </template>
    <div class="body">
      <div v-if="detailData" ref="formRef" class="form">
        <div class="title">基本信息</div>
        <div class="info_list">
          <div class="info_item">
            <div class="label">配件编号:</div>
            <div class="value">{{ detailData.code }}</div>
          </div>
          <div class="info_item">
            <div class="label">工单单号:</div>
            <div class="value">{{ detailData.workNo }}</div>
          </div>
          <div class="info_item">
            <div class="label">申请类型:</div>
            <div class="value">{{ options6[detailData.type - 1].name }}</div>
          </div>
          <div v-if="detailData.type === 2" class="info_item">
            <div class="label">网点配件类型:</div>
            <div class="value">{{ getNetworkSpareTypeRenderTxt(detailData.networkSpareType) }}</div>
          </div>
        </div>
        <div class="content">
          <el-form label-position="top">
            <div class="warehouse_back_container">
              <!-- 收货地址类型 -->
              <el-form-item label="收货地址类型" class="address_type">
                <el-select
                  v-model="dataList.receiptAddrType"
                  clearable
                  placeholder="收货地址类型"
                  @change="changeAddrType"
                >
                  <el-option label="工单客户" :value="1" />
                  <el-option label="网点" :value="2" />
                </el-select>
              </el-form-item>

              <!-- 旧件处理方式 -->
              <el-form-item label="旧件处理方式" class="old_handle_method">
                <el-select
                  v-model="dataList.oldCopeWay"
                  placeholder="旧件处理方式"
                  :disabled="isDisableCheckStatusSelect"
                  @change="changeoldCopeWay"
                >
                  <el-option label="废弃" :value="1" />
                  <el-option label="旧件退回" :value="2" />
                </el-select>
              </el-form-item>

              <el-form-item v-if="dataList.oldCopeWay === 2" label="退回仓库">
                <el-select
                  v-model="dataList.storeId"
                  :loading="getWarehouseEntryOptionListLoading"
                  placeholder="请选择仓库"
                  filterable
                  :filter-method="handleGetWarehouseOptionList"
                  @change="changeoldCopeWay(1)"
                >
                  <template #header>
                    <div class="select_header">
                      <el-input
                        v-model.trim="getReturnWareHouseOptionsParam.name"
                        placeholder="请输入关键字"
                        @keyup.enter="getReturnWareHouseOptionsFn"
                      />
                      <h-plain-button @click="getReturnWareHouseOptionsFn">搜索</h-plain-button>
                    </div>
                  </template>
                  <el-option
                    v-for="item in warehouseEntryOptionList"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                    @click="handleChangeReturnWareHouse(item)"
                  />
                </el-select>
                <div v-if="dataList.storeId" class="back_warehouse_info_list">
                  <div class="info_item">
                    <div class="label">姓名:</div>
                    <div class="value">{{ dataList.oldReceiptName }}</div>
                  </div>
                  <div class="info_item">
                    <div class="label">手机号:</div>
                    <div class="value">{{ dataList.oldReceiptPhone }}</div>
                  </div>
                  <div class="info_item">
                    <div class="label">仓库地址:</div>
                    <div class="value">
                      {{
                        dataList.oldReceiptProvince +
                        dataList.oldReceiptCity +
                        dataList.oldReceiptArea +
                        dataList.oldReceiptTown +
                        dataList.oldReceiptAddress
                      }}
                    </div>
                  </div>
                </div>
              </el-form-item>

              <el-form-item
                v-if="
                  isEnableStorePosition(dataList.storeId, warehouseEntryOptionList) &&
                  dataList.oldCopeWay === 2
                "
                label="退回仓位"
              >
                <el-select
                  v-model="dataList.storePositionId"
                  :disabled="!isEnableStorePosition(dataList.storeId, warehouseEntryOptionList)"
                  :loading="loading"
                  placeholder="请选择退回仓位"
                >
                  <template #header>
                    <div class="select_header">
                      <el-input
                        v-model.trim="getStorePositionOptionsKeyword"
                        placeholder="请输入关键字"
                        @keyup.enter="getStorePositionOptionsFn(dataList.storeId)"
                      />
                      <h-plain-button @click="getStorePositionOptionsFn(dataList.storeId)"
                        >搜索</h-plain-button
                      >
                    </div>
                  </template>
                  <el-option
                    v-for="item in sotrePositionOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>

            <div class="personal_phone_container">
              <!-- 收货人姓名 -->
              <el-form-item label="收货人姓名" class="person_name">
                <el-input v-model.trim="dataList.receiptName" clearable placeholder="收货人姓名" />
              </el-form-item>

              <!-- 收货人手机号 -->
              <el-form-item label="收货人手机号" class="phone">
                <el-input
                  v-model.trim="dataList.receiptPhone"
                  :maxlength="11"
                  clearable
                  placeholder="收货人手机号"
                  @input="dataList.receiptPhone = dataList.receiptPhone.replace(/\D/g, '')"
                />
              </el-form-item>

              <el-form-item label="审核备注" class="remark">
                <el-input
                  v-model.trim="dataList.remark"
                  clearable
                  maxlength="200"
                  placeholder="填写备注信息"
                  show-word-limit
                  size="small"
                  type="textarea"
                  resize="both"
                />
              </el-form-item>
            </div>

            <div class="address_container">
              <el-form-item label="收货人地址">
                <SingleAddress ref="addrsDom" :address="addrs" />
              </el-form-item>
              <el-form-item label="详细地址">
                <el-input
                  v-model.trim="dataList.receiptAddress"
                  :rows="2"
                  clearable
                  maxlength="200"
                  placeholder="收货人详细地址"
                  show-word-limit
                  size="small"
                  type="textarea"
                  resize="both"
                />
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <div class="table">
        <el-table :border="true" :data="dataList.workSpareMaterials" resizable stripe height="100%">
          <el-table-column fixed="left" label="序号" width="50" type="index" :align="'center'" />

          <!-- 收支类型 -->
          <el-table-column label="收支类型" width="150">
            <template #default="{ row, $index }">
              <el-select
                v-model="row.type"
                placeholder="收支类型"
                @change="handleIncomeOrPayTypeChange($index)"
              >
                <el-option
                  v-for="item in incomeOrPayTypeOptional"
                  :key="item.value"
                  :value="item.value"
                  :label="item.name"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 申请的配件物料 -->
          <!-- <el-table-column label="申请的配件物料" show-overflow-tooltip width="240">
            <template v-slot="i">
              {{ i.row.applySpareModel }}、{{ i.row.applySpareSpec }}、{{
                i.row.applySpareSpecCode
              }}
            </template>
          </el-table-column> -->

          <!-- 配件编号 -->
          <el-table-column label="配件编号" width="200">
            <template #default="{ row, $index }">
              <el-popover
                placement="bottom-start"
                :width="700"
                :visible="row.popoverVisible"
                popper-style="padding: 0;"
                :show-arrow="false"
              >
                <template #reference>
                  <el-input
                    v-model.trim="row.code"
                    placeholder="请输入配件编号"
                    @input="(keyword: string) => handleSparePartCodeInput(keyword, $index)"
                    @blur="row.popoverVisible = false"
                  />
                </template>

                <el-table
                  v-loading="getGoodListLoading"
                  :border="true"
                  :data="goodList"
                  max-height="400"
                  @row-click="(row: GoodItem) => handleSparePartOptionClick(row, $index)"
                >
                  <!-- 序号 -->
                  <el-table-column type="index" label="序号" :align="'center'" width="50" />

                  <!-- 物料编号 -->
                  <el-table-column prop="code" label="物料编号" width="140" />

                  <!-- 物料名称 -->
                  <el-table-column
                    show-overflow-tooltip
                    prop="name"
                    label="物料名称"
                    min-width="160"
                  />

                  <!-- 物料分类 -->
                  <el-table-column prop="type" label="物料分类" width="120" />
                </el-table>
              </el-popover>
            </template>
          </el-table-column>

          <!-- 配件名称 -->
          <el-table-column label="配件名称" width="160">
            <template #default="{ row }">
              <el-input :model-value="row.sparePartName" disabled />
            </template>
          </el-table-column>

          <!-- 规格 -->
          <el-table-column label="规格" width="180">
            <template #default="{ row, $index }">
              <el-select
                v-model="row.specId"
                :loading="getGoodSpecLoading"
                placeholder="请选择"
                @change="(id: any) => handlePartSpecClick(id, $index)"
              >
                <template #header>
                  <div class="select_header">
                    <el-input
                      v-model.trim="getPartSpecOptionsKeyword"
                      placeholder="请输入关键字"
                      @keyup.enter="getPartSpecOptionsFn(row.spareId || '', $index)"
                    />
                    <HPlainButton @click="getPartSpecOptionsFn(row.spareId || '', $index)">
                      搜索
                    </HPlainButton>
                  </div>
                </template>
                <el-option
                  v-for="item in row.partSpecOptions"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                  @click="handlePartSpecClick(item, $index)"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 规格编码 -->
          <!-- <el-table-column label="规格编码" width="180" prop="model">
            <template #default="scope">
              <el-input :value="scope.row.checkSpareSpecCode" disabled />
            </template>
          </el-table-column> -->

          <!-- 物料质保状态  先隐藏-->
          <!-- <el-table-column label="质保状态" width="150">
            <template #default="scope">
              <el-select
                v-model="scope.row.overinsured"
                filterable
                placeholder="质保状态"
                @change="handleIncomeOrPayTypeChange(scope.$index)"
              >
                <el-option label="保内" :value="false" />
                <el-option label="保外" :value="true" />
              </el-select>
            </template>
          </el-table-column> -->

          <!-- 申请数量 -->
          <el-table-column label="申请数量" width="90">
            <template #default="{ row }">
              <el-input v-model.trim.number="row.qty" clearable placeholder="数量" />
            </template>
          </el-table-column>

          <!-- 公司承担 -->
          <el-table-column label="公司承担费用单价" width="140">
            <template #default="{ row, $index }">
              <el-input
                v-model.trim="row.price"
                clearable
                style="border-radius: 2px"
                :disabled="row.type !== 1"
                @keyup="(e: Event) => handlePriceInput(e, $index)"
              />
            </template>
          </el-table-column>

          <!-- 客户承担 -->
          <el-table-column label="收取客户费用单价" width="140">
            <template #default="{ row, $index }">
              <el-input
                v-model.trim="row.customerUndertakePrice"
                clearable
                style="border-radius: 2px"
                :disabled="row.type !== 2"
                @keyup="(e: Event) => handlecustomerUndertakePriceInput(e, $index)"
              />
            </template>
          </el-table-column>

          <!-- 网点承担 -->
          <el-table-column label="支付网点费用单价" width="140">
            <template #default="{ row, $index }">
              <el-input
                v-model.trim="row.networkUndertakePrice"
                clearable
                style="border-radius: 2px"
                :disabled="row.type !== 3"
                @keyup="(e: Event) => handlenetworkUndertakePriceInput(e, $index)"
              />
            </template>
          </el-table-column>

          <!-- 仓库 -->
          <template v-if="!(detailData && detailData.networkSpareType === 3)">
            <el-table-column label="出库仓库" width="180">
              <template #default="{ row, $index }">
                <el-select
                  v-model="row.storeId"
                  :loading="loading"
                  placeholder="请选择"
                  :disabled="
                    detailData && detailData.type === 2 && detailData.networkSpareType === 1
                  "
                  @change="changeSeleStoreId(row, $index)"
                >
                  <template #header>
                    <div class="select_header">
                      <el-input
                        v-model.trim="getReturnWareHouseOptionsParam.name"
                        placeholder="请输入关键字"
                        @keyup.enter="getReturnWareHouseOptionsFn"
                      />
                      <HPlainButton @click="getReturnWareHouseOptionsFn">搜索</HPlainButton>
                    </div>
                  </template>
                  <el-option
                    v-for="item in returnWareHouseOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 仓位 -->
            <el-table-column label="仓位" width="120">
              <template #default="{ row, $index }">
                <el-select
                  v-model="row.storePositionId"
                  :disabled="!isEnableStorePosition(row.storeId, returnWareHouseOptions)"
                  :loading="loading"
                  placeholder="请选择"
                  @change="changeSelestorePositionId(row, $index)"
                >
                  <template #header>
                    <div class="select_header">
                      <el-input
                        v-model.trim="getTableStorePositionOptionsKeyword"
                        placeholder="请输入关键字"
                        @keyup.enter="getTableStorePositionOptionsFn(row.storeId, $index)"
                      />
                      <HPlainButton @click="getTableStorePositionOptionsFn(row.storeId, $index)">
                        搜索
                      </HPlainButton>
                    </div>
                  </template>
                  <el-option
                    v-for="item in row.storePositionOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 即时库存 -->
            <el-table-column label="即时库存" width="180">
              <template #default="{ row }">
                <span>{{ row.systemStock }}</span>
              </template>
            </el-table-column>
          </template>

          <!-- 备注 -->
          <el-table-column label="备注" max-width="150" min-width="140">
            <template #default="{ row }">
              <el-input v-model.trim="row.remark" clearable placeholder="填写备注" />
            </template>
          </el-table-column>

          <!-- 审核状态 -->
          <el-table-column label="审核" width="120" fixed="right" :align="'center'">
            <template #default="{ row }">
              <el-select
                v-model="row.status"
                filterable
                placeholder="审核"
                @change="handleSelectCheckStatus"
              >
                <el-option label="通过" :value="2" />
                <el-option label="驳回" :value="3" />
              </el-select>
            </template>
          </el-table-column>

          <!-- 附件 -->
          <el-table-column :width="annexColumnWidth" label="附件(最多上传8个)">
            <template #default="{ row, $index }">
              <div class="file_list">
                <template v-for="(img, index) in row.images" :key="index">
                  <h-image
                    :width="60"
                    :height="37.5"
                    :src="img.image"
                    :initial-index="index"
                    :preview-src-list="row.images.map((item) => item.image)"
                    fit="scale-down"
                    :padding="2"
                    :show-del-btn="!img.id"
                    :mask-btn-gap="3"
                    @del="handleDelFile($index, index)"
                  />
                </template>
                <h-image
                  v-if="row.images.length < 8"
                  :src="uploadPlaceholderImg"
                  :width="60"
                  :height="37.5"
                  :padding="2"
                >
                  <el-upload
                    :auto-upload="false"
                    :on-change="(file) => handleUploadPicture(file, $index)"
                    :show-file-list="false"
                    accept="image/*"
                    action="#"
                    multiple
                  >
                    <div style="height: 35.5px; line-height: 35.5px">
                      <i class="iconfont icon-img-upload" style="color: #fff; font-size: 24px"></i>
                    </div>
                  </el-upload>
                </h-image>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <HButton is-modal type="primary" :disabled="$route.query.isArchive == 'true'" @click="onSave">
        审核
      </HButton>
      <HButton is-modal @click="onCancel">取消</HButton>
    </template>
  </h-drawer>
  <HModal v-model="dialogVisible" title="查看附件">
    <iframe :src="`${dialogImageUrl}`" style="height: 660px; width: 100%"></iframe>
  </HModal>
</template>

<script lang="ts" setup>
  import { nextTick, ref, toRefs, watch } from 'vue'
  import { sparePageSelect } from '@/api/code'
  import {
    getGoodsStock,
    storeEmpAddressPageSelect,
    storePageSelect,
    storePositionPageSelect,
  } from '@/api/store'
  import {
    checkOrderSpare,
    getBeforeCheckOrderSpareDetail,
    getOrderNetworkAddress,
    getOrderSpareMaterial,
    getWorkUserAddress,
    spareUpdate,
  } from '@/api/parts'
  import { orderAnnexUpload } from '@/api/upload'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { UploadFile, UploadRawFile } from 'element-plus'
  import { checkNum, keepPartInteger } from '@/utils/validate'
  import _ from 'lodash'
  import {
    PartOptions,
    PartSpecOptions,
    ReturnWareHouseOptions,
    StorePositionOptions,
  } from './types'
  import uploadPlaceholderImg from '@/assets/image/avatar_upload_default.png'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { useGetNetworkWarehouse } from '@/services/pages/storage/useWarehouse'
  import { useGetWarehouseAndPersonAddressList } from '@/services/pages/storage/useWarehouseOut'
  import { useGetGoodList } from '@/services/pages/good/useGood'
  import { useGetGoodSpecService } from '@/services/module/product/useProduct'

  const { goodList, getGoodListParam, getGoodListLoading, getGoodList } = useGetGoodList()
  const { warehouse, getWarehouseLoading, getWarehouse } = useGetNetworkWarehouse()
  const {
    list: warehouseEntryOptionList,
    getListParam: getWarehouseEntryOptionListParam,
    getListLoading: getWarehouseEntryOptionListLoading,
    getList: getWarehouseEntryOptionList,
  } = useGetWarehouseAndPersonAddressList()
  const { goodSpecList, getGoodSpecParam, getGoodSpecLoading, getProductSpecList } =
    useGetGoodSpecService()

  const props = defineProps({
    modelValue: Boolean,
    partsId: {
      type: String,
      required: true,
    },
    workId: {
      type: String,
      required: true,
    },
    networkId: {
      type: String,
      required: true,
    },
    modalType: {
      type: Number,
      default: () => 1,
    },
  })

  // 附件列宽
  const annexColumnWidth = ref(130)

  // 设置附件列的宽度
  const setAnnexColumnWidth = () => {
    let maxImageLength = Math.max(
      ...dataList.value.workSpareMaterials.map((item) => item.images.length),
    )

    // 在图片数量小于8张时要把上传按钮的宽度计算进去
    if (maxImageLength < 8) {
      maxImageLength += 1
    }

    // 这是为了解决删剩一张图时，列宽会变得很小，导致标题会换行
    if (maxImageLength > 0) {
      annexColumnWidth.value = maxImageLength * 60 + (maxImageLength - 1) * 8 + 24
    }

    if (annexColumnWidth.value < 130) {
      annexColumnWidth.value = 130
    }
  }

  // 收支类型选项
  const incomeOrPayTypeOptional = [
    { name: '公司承担', value: 1 },
    { name: '收取客户', value: 2 },
    { name: '支付网点', value: 3 },
  ]

  /**
   * 获取配件详情
   * @param index
   */
  const getSpareDetail = (index: number) => {
    return dataList.value.workSpareMaterials[index]
  }

  /**
   * 收支类型更新事件
   * @param index - 配件索引
   */
  const handleIncomeOrPayTypeChange = (index: number) => {
    const { partSpecOptions, specId, overinsured, type } = dataList.value.workSpareMaterials[index]

    // 提取费用项目的金额
    let price = 0
    if (dataList.value.workSpareMaterials[index].specId) {
      const feeProject = partSpecOptions.find((item) => item.id === specId)
      if (feeProject) {
        price = overinsured ? feeProject.overPrice : feeProject.price
      }
    }

    dataList.value.workSpareMaterials[index].customerUndertakePrice = 0
    dataList.value.workSpareMaterials[index].price = 0
    dataList.value.workSpareMaterials[index].networkUndertakePrice = 0

    switch (type) {
      case 1:
        dataList.value.workSpareMaterials[index].price = price
        break
      case 2:
        dataList.value.workSpareMaterials[index].customerUndertakePrice = price
        break
      case 3:
        dataList.value.workSpareMaterials[index].networkUndertakePrice = price
        break
    }
  }

  const { partsId, workId } = toRefs(props)
  const dialogVisible = ref(false)
  const dialogImageUrl = ref(null)

  // 仓库下拉选项
  const returnWareHouseOptions = ref<Array<ReturnWareHouseOptions>>([])

  const loading = ref(false)
  // const loading2 = ref(false)
  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update-list'): void
  }>()

  // 网点配件类型
  const networkSpareTypeList = [
    { name: '网点仓', value: 1 },
    {
      name: '自购配件',
      value: 3,
    },
  ]

  // 申请类型
  const options6 = [
    { name: '公司配件', value: 1 },
    { name: '外部配件', value: 2 },
  ]
  let dataList = ref({
    id: null, //工单配件ID
    oldCopeWay: 2, //旧件处理方式：1-废弃，2-旧件退回,示例值(2)
    oldReceiptAddress: '', //旧件收货人详细地址
    oldReceiptArea: '', //旧件收货地址-县/区
    oldReceiptCity: '', //旧件收货地址-市
    oldReceiptName: '', //旧件收货人姓名
    oldReceiptPhone: '', //旧件收货人手机号
    oldReceiptProvince: '', //旧件收货地址-省
    oldReceiptTown: '', //旧件收货地址-镇
    receiptAddrType: null, //收货地址类型：1-工单客户地址，2-网点地址
    receiptAddress: '', //收货人详细地址
    receiptArea: '', //收货地址-县/区
    receiptCity: '', //收货地址-市
    receiptName: '', //收货人姓名
    receiptPhone: '', //收货人手机号
    receiptProvince: '', //收货地址-省
    receiptTown: '', //收货地址-镇
    remark: '', //备注
    storeId: null, //旧件退回仓库ID
    storePositionId: null, // 旧件退回仓库仓位ID
    userOrNetworkId: null, //客户/网点ID
    workSpareMaterials: [
      //工单配件物料
      {
        delImageIds: [], //删除的工单费用图片对象ID
        id: null, //配件物料ID
        images: [
          {
            id: 0,
            image: '',
            file: null,
          },
        ],
        overinsured: false, //质保状态：false-保内，true-保外
        price: 0, // 公司承担费用
        qty: 1, //配件物料数量,示例值(1)
        remark: '', //备注
        spareId: '', //配件ID
        specId: '', //配件规格ID
        status: 2, //配件物料审核状态：2-已通过，3-已驳回,示例值(2)
        storeId: '', //仓库ID
        storePositionId: '', //仓位id
        type: 1, //	结算类型：1-向网点收取，2-向网点支付，3-向客户收取，4-向客户支付,示例值(1)
        spareSelect: [], //配件
        spareSpecSelect: [], //规格
        checkSpareSpec: '',
        checkSpareSpecCode: '',
        storePageSelect: [], //仓库下拉列表
        storePositionPageSelect: [], //仓位下拉列表
        checkSpareModel: '',
        systemStock: 0, //即时库存
        customerUndertakePrice: 0, // 客户承担
        networkUndertakePrice: 0, // 网点承担
        partSpecOptions: [],
        storePositionOptions: [],
        popoverVisible: false,
        sparePartName: '',
        code: '',
      },
    ],
  })
  const detailData = ref(null) //详情
  const addrsDom = ref()
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 获取退回仓库下拉选项请求参数
  const getReturnWareHouseOptionsParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  // 获取退回仓库下拉选项加载
  const getReturnWareHouseOptionsLoading = ref(false)

  // 获取退回仓库下拉选项方法
  const getReturnWareHouseOptionsFn = async (networkSpareType: 0 | 1 | 2 = 0) => {
    getReturnWareHouseOptionsLoading.value = true
    const res = await storeEmpAddressPageSelect(
      getReturnWareHouseOptionsParam.value,
      networkSpareType,
    )
    if (res.data.success) {
      returnWareHouseOptions.value = res.data.data.rows
    } else {
      HMessageBox.error(res.data.message)
    }
    getReturnWareHouseOptionsLoading.value = false
  }

  /**
   * 退回仓库下拉选项点击事件
   * @param {object} item - 人员、地址、仓库信息
   */
  const handleChangeReturnWareHouse = (item: ReturnWareHouseOptions) => {
    dataList.value.oldReceiptName = item.userName
    dataList.value.oldReceiptPhone = item.phone
    dataList.value.oldReceiptAddress = item.address
    dataList.value.oldReceiptProvince = item.province
    dataList.value.oldReceiptCity = item.city
    dataList.value.oldReceiptArea = item.area
    dataList.value.oldReceiptTown = item.town
    dataList.value.storePositionId = null
    sotrePositionOptions.value = []
    if (isEnableStorePosition(item.id, returnWareHouseOptions.value)) {
      getStorePositionOptionsFn(item.id)
    }
  }

  // 获取仓位下拉选项请求关键字
  const getStorePositionOptionsKeyword = ref('')

  // 仓位下拉选项
  const sotrePositionOptions = ref<Array<StorePositionOptions>>([])

  /**
   * 获取仓位下拉选项方法
   * @param {string} query - 关键字
   * @param {string} id - 仓库id
   */
  const getStorePositionOptionsFn = async (id: string) => {
    if (id) {
      const data = {
        limit: 0,
        page: 0,
        name: getStorePositionOptionsKeyword.value,
      }
      const res = await storePositionPageSelect(data, id)
      sotrePositionOptions.value = res.data.data.rows
    }
  }

  // 获取表格的仓位下拉选项关键字
  const getTableStorePositionOptionsKeyword = ref('')

  /**
   * 获取表格的仓位下拉选项方法
   * @param {string} id - 仓库id
   * @param {number} index - 操作的表格行的索引
   */
  const getTableStorePositionOptionsFn = async (id: string, index: number) => {
    const param = {
      name: getTableStorePositionOptionsKeyword.value,
      limit: 0,
      page: 0,
    }
    const res = await storePositionPageSelect(param, id)
    dataList.value.workSpareMaterials[index].storePositionOptions = res.data.data.rows
  }

  //仓库下拉变化
  const changeSeleStoreId = (row: (typeof dataList.value.workSpareMaterials)[0], index: number) => {
    row.storePositionId = null

    // 判断是否启用仓位
    if (isEnableStorePosition(row.storeId, returnWareHouseOptions.value)) {
      getTableStorePositionOptionsFn(row.storeId, index)
    } else {
      changeSelestorePositionId(row, index)
    }
  }

  // 仓位下拉变化
  const changeSelestorePositionId = (
    row: (typeof dataList.value.workSpareMaterials)[0],
    index: null | number = null,
  ) => {
    if (row.spareId && row.specId && row.storeId) {
      let data: {
        goodsId: string
        goodsSpecId: string
        storeId: string
        storePositionId: string
        type: 1 | 2
      } = {
        goodsId: row.spareId, //商品ID
        goodsSpecId: row.specId, //商品规格ID
        storeId: row.storeId, //仓库ID
        storePositionId: row.storePositionId || '', //仓库仓位ID，当仓库启用仓位时，此字段必传
        type: 2, //商品类型：1-成品，2-配件
      }
      dataList.value.workSpareMaterials[index].systemStock = 0
      if (!isEnableStorePosition(row.storeId, returnWareHouseOptions.value)) {
        data.storePositionId = row.storePositionId
      }
      getGoodsStock(data).then((res) => {
        if (res) {
          if (res.data.code === 20000) {
            if (res.data.data.row.id && !Number(getSpareDetail(index).price)) {
              dataList.value.workSpareMaterials[index].price = res.data.data.row.price
            }
            dataList.value.workSpareMaterials[index].systemStock = res.data.data.row.systemStock
          }
        }
      })
    }
  }
  // 判断是否启用仓位
  const isEnableStorePosition = (id: string, storePositions: Array<ReturnWareHouseOptions>) => {
    if (storePositions.length <= 0) {
      return false
    }
    const storePosition = storePositions.find((item) => item.id === id)
    if (!storePosition) {
      return false
    }
    return storePosition.enableStorePosition
  }
  // 地址类型变化
  const changeAddrType = (val) => {
    switch (val) {
      case 1:
        getWorkUserAddressData()
        break
      case 2:
        getOrderNetworkAddressData()
        break
      default:
        dataList.value.receiptName = ''
        dataList.value.receiptPhone = ''
        dataList.value.receiptAddress = ''
        dataList.value.receiptProvince = ''
        dataList.value.receiptCity = ''
        dataList.value.receiptArea = ''
        dataList.value.receiptTown = ''
        addrs.value = {
          province: '',
          city: '',
          area: '',
          town: '',
        }
        addrsDom.value.clearSelectAddr()
        break
    }
  }

  // 旧件处理方式变化
  const changeoldCopeWay = (val) => {
    switch (val) {
      case 1:
        dataList.value.oldReceiptName = ''
        dataList.value.oldReceiptPhone = ''
        dataList.value.oldReceiptAddress = ''
        dataList.value.oldReceiptProvince = ''
        dataList.value.oldReceiptCity = ''
        dataList.value.oldReceiptArea = ''
        dataList.value.oldReceiptTown = ''
        getStorePositionOptionsFn(dataList.value.storeId)
        break
      case 2:
        break
    }
  }
  // 获取用户地址
  const getWorkUserAddressData = async () => {
    const res = await getWorkUserAddress(workId.value)
    if (res.data.success) {
      dataList.value.userOrNetworkId = res.data.data.row.id
      dataList.value.receiptName = res.data.data.row.name
      dataList.value.receiptPhone = res.data.data.row.phone
      dataList.value.receiptAddress = res.data.data.row.address
      dataList.value.receiptProvince = res.data.data.row.province
      dataList.value.receiptCity = res.data.data.row.city
      dataList.value.receiptArea = res.data.data.row.area
      dataList.value.receiptTown = res.data.data.row.town
      addrs.value = {
        province: dataList.value.receiptProvince,
        city: dataList.value.receiptCity,
        area: dataList.value.receiptArea,
        town: dataList.value.receiptTown,
      }
    } else {
      HMessageBox.error(res.data.message)
    }
  }
  // 获取网点地址
  const getOrderNetworkAddressData = async () => {
    const res = await getOrderNetworkAddress(workId.value)
    if (res.data.success) {
      dataList.value.userOrNetworkId = res.data.data.row.id
      dataList.value.receiptName = res.data.data.row.name
      dataList.value.receiptPhone = res.data.data.row.phone
      dataList.value.receiptAddress = res.data.data.row.address
      dataList.value.receiptProvince = res.data.data.row.province
      dataList.value.receiptCity = res.data.data.row.city
      dataList.value.receiptArea = res.data.data.row.area
      dataList.value.receiptTown = res.data.data.row.town
      addrs.value = {
        province: dataList.value.receiptProvince,
        city: dataList.value.receiptCity,
        area: dataList.value.receiptArea,
        town: dataList.value.receiptTown,
      }
    } else {
      HMessageBox.error(res.data.message)
    }
  }

  // 获取配件下拉选项请求参数
  const getPartOptionsKeyword = ref('')

  // 配件下拉选项
  const partOptions = ref<Array<PartOptions>>([])

  // 获取配件下拉选项加载
  const getPartOptionsLoading = ref(false)

  /**
   * 获取下拉选项方法
   */
  const getPartOptionsFn = async () => {
    getPartOptionsLoading.value = true
    const data = {
      limit: 100,
      page: 1,
      name: getPartOptionsKeyword.value,
    }
    const res = await sparePageSelect(data)
    partOptions.value = res.data.data.rows
    getPartOptionsLoading.value = false
  }

  /**
   * 配件下拉选项点击事件
   * @param {object} val - 配件信息
   * @param {number} index - 操作的表格行的索引
   */
  // const handlePartOptionClick = (val: PartOptions, index: number) => {
  //   dataList.value.workSpareMaterials[index].checkSpareModel = val.model
  // }

  /**
   * 配件选择事件
   * @param {string} id - 配件id
   * @param {number} index - 操作的表格行的索引
   */
  // const handleChangePart = (id: string, index: number) => {
  //   dataList.value.workSpareMaterials[index].specId = null
  //   dataList.value.workSpareMaterials[index].checkSpareSpecCode = ''
  //   dataList.value.workSpareMaterials[index].checkSpareSpec = ''
  //   dataList.value.workSpareMaterials[index].spareSpecSelect = []
  //   if (id) {
  //     getPartSpecOptionsFn(id, index)
  //   }
  // }

  // 获取配件规格下拉选项加载
  // const getPartSpecOptionsLoading = ref(false)

  // 获取配件规格关键字
  const getPartSpecOptionsKeyword = ref('')

  /**
   * 获取配件规格下拉选项方法
   * @param {string} id - 配件id
   * @param {number} index - 操作的行的索引
   */
  const getPartSpecOptionsFn = async (id: string, index: number) => {
    getGoodSpecParam.value = {
      name: '',
      page: 1,
      limit: 100,
      code: '',
    }

    const good = goodList.value.find((item) => item.id === id)
    if (good) {
      await getProductSpecList(good.goodsType === 1 ? 'product' : 'material', id)
      dataList.value.workSpareMaterials[index].partSpecOptions = goodSpecList.value
    }
  }

  // 仓库下拉数据
  const getstorePageSelect = async (val: string, index: number) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    let networkSpareType = null
    if (detailData.value?.type == 1) {
      networkSpareType = 0
    } else {
      networkSpareType = detailData.value?.networkSpareType
    }
    const res = await storePageSelect(data, networkSpareType)
    if (res) {
      dataList.value.workSpareMaterials[index].storePageSelect = res.data.data.rows
      dataList.value.workSpareMaterials[index].storePositionId = null
    }
  }

  // 保存加载
  const saveLoading = ref(false)

  // 保存
  async function onSave() {
    if (props.modalType == 1) {
      if (dataList.value.oldCopeWay == null) {
        dataList.value.oldCopeWay = 0
      } else if (dataList.value.oldCopeWay == 2) {
        if (dataList.value.workSpareMaterials.some((o) => o.status == 2)) {
          if (!dataList.value.storeId) {
            HMessageBox.error('请选择退回的仓库！')
            return
          }
          if (
            !dataList.value.storePositionId &&
            dataList.value.storeId &&
            isEnableStorePosition(dataList.value.storeId, returnWareHouseOptions.value)
          ) {
            HMessageBox.error('请选择退回仓库的仓位！')
            return
          }
        }
      }
      if (dataList.value.workSpareMaterials.some((o) => o.status == 1)) {
        HMessageBox.error('工单配件存在未审核的配件数据，请审核后重新提交')
        return
      }
    } else {
      if (dataList.value.oldCopeWay == null) {
        dataList.value.oldCopeWay = 0
      }
    }

    for (const key in dataList.value.workSpareMaterials) {
      let imgobj = dataList.value.workSpareMaterials[key]

      saveLoading.value = true
      const __images: Array<UploadRawFile> = imgobj.images.map((item) => item.file)
      if (__images.length > 0) {
        const res = await orderAnnexUpload(__images)
        dataList.value.workSpareMaterials[key].images = res.data.data.rows.map((item) => {
          return { id: null, image: item, file: null }
        })
      }
    }
    /**
     * 先用Partial<typeof item>将所有属性都变成可选属性
     * 然后再删除规格下拉选项属性
     * 最后再使用Required<typeof __item>将所有属性变成必选属性
     * 如果直接删除会引起typescript的报错
     * 这种处理方式不好，应该使用接口进行类型声明，这样就不用这么麻烦，等后面改到再优化
     */
    dataList.value.workSpareMaterials = dataList.value.workSpareMaterials.map((item) => {
      const __item: Partial<typeof item> = _.cloneDeep(item)
      delete __item.partSpecOptions
      delete __item.storePositionOptions
      return __item as Required<typeof __item>
    })
    let checkResult = ''
    if (props.modalType == 1) {
      checkResult = await checkOrderSpare(dataList.value)
    } else {
      checkResult = await spareUpdate(dataList.value)
    }

    if (checkResult.data.success) {
      HMessage.success(props.modalType == 1 ? '审核成功' : '编辑成功')
      emits('update-list')
      onCancel()
    } else {
      HMessageBox.error(checkResult.data.message)
    }
    saveLoading.value = false
  }

  // 获取详情加载
  const getDetailLoading = ref(false)

  /**
   * 获取详情
   * @param {string} id - 配件id
   */
  const getBeforeCheckOrderSpareDetailInfo = async (id: string) => {
    getDetailLoading.value = true
    const res = await getBeforeCheckOrderSpareDetail(id)
    if (res.data.success) {
      detailData.value = res.data.data.row
      dataList.value = { ...dataList.value, ...detailData.value }
      if (dataList.value.oldCopeWay == 0) {
        dataList.value.oldCopeWay = 2
        await getPartOptionsFn()
      }
      getDetailLoading.value = false
      setTimeout(async () => {
        await nextTick(async () => {
          if (dataList.value.receiptAddrType == 1) {
            await getWorkUserAddressData()
          } else if (dataList.value.receiptAddrType == 2) {
            await getOrderNetworkAddressData()
          }
        })
        dataList.value.receiptPhone = res.data.data.row.receiptPhone
      }, 500)
    } else {
      HMessageBox.error(res.data.message)
      getDetailLoading.value = false
    }
  }

  // 获取列表详情加载
  const getListDetailLoading = ref(false)

  /**
   * 获取列表详情
   */
  const getOrderSpareMaterialList = async (id: string) => {
    getListDetailLoading.value = true
    const orderSpareMaterial = await getOrderSpareMaterial(id)
    if (orderSpareMaterial.data.success) {
      dataList.value.workSpareMaterials = orderSpareMaterial.data.data.rows.map((material) => {
        return {
          ...material,
          delImageIds: [],
          storePositionId: '',
          spareSelect: false,
          spareSpecSelect: false,
          popoverVisible: false,
          partSpecOptions: [],
          storePositionOptions: [],
          storePageSelect: false,
          storePositionPageSelect: false,
          systemStock: 0,
          customerUndertakePrice: 0,
          networkUndertakePrice: 0,
          sparePartName: '',
        }
      })
      for (let i = 0; i < orderSpareMaterial.data.data.rows.length; i++) {
        dataList.value.workSpareMaterials[i].status =
          orderSpareMaterial.data.data.rows[i].status == 1
            ? 2
            : orderSpareMaterial.data.data.rows[i].status
        if (orderSpareMaterial.data.data.rows[i].storeId == '0') {
          dataList.value.workSpareMaterials[i].storeId = ''
        }

        await getPartSpecOptionsFn(orderSpareMaterial.data.data.rows[i].spareId, i)
        if (orderSpareMaterial.data.data.rows[i].spareId != '0') {
          dataList.value.workSpareMaterials[i].checkSpareSpec =
            orderSpareMaterial.data.data.rows[i].applySpareSpec
          dataList.value.workSpareMaterials[i].checkSpareSpecCode =
            orderSpareMaterial.data.data.rows[i].applySpareSpecCode
        } else {
          dataList.value.workSpareMaterials[i].spareId = ''
          dataList.value.workSpareMaterials[i].specId = ''
        }
        if (detailData.value && detailData.value.networkSpareType != 3) {
          await getstorePageSelect('', i)
        }
      }
      setAnnexColumnWidth()
    } else {
      HMessageBox.error(orderSpareMaterial.data.message)
    }
    getListDetailLoading.value = false
  }

  /**
   * 配件规格点击事件
   * @param {object} val - 配件规格信息
   * @param {number} index - 操作的表格行的索引
   */
  const handlePartSpecClick = (val: PartSpecOptions, index: number) => {
    if (Object.prototype.toString.call(val) === '[object Object]') {
      dataList.value.workSpareMaterials[index].checkSpareSpec = val.name
      dataList.value.workSpareMaterials[index].checkSpareSpecCode = val.specSkuCode
    } else {
      if (!val) {
        dataList.value.workSpareMaterials[index].checkSpareSpecCode = ''
        dataList.value.workSpareMaterials[index].checkSpareSpec = ''
      }
    }

    const price = dataList.value.workSpareMaterials[index].overinsured ? val.overPrice : val.price
    dataList.value.workSpareMaterials[index].price = 0
    dataList.value.workSpareMaterials[index].networkUndertakePrice = 0
    dataList.value.workSpareMaterials[index].customerUndertakePrice = 0
    if (dataList.value.workSpareMaterials[index].type === 1) {
      dataList.value.workSpareMaterials[index].price = price
    }
    if (dataList.value.workSpareMaterials[index].type === 2) {
      dataList.value.workSpareMaterials[index].customerUndertakePrice = price
    }
    if (dataList.value.workSpareMaterials[index].type === 3) {
      dataList.value.workSpareMaterials[index].networkUndertakePrice = price
    }
  }

  /**
   * 上传图片事件
   * @param file - 文件
   * @param index - 配件索引
   */
  const handleUploadPicture = (file: UploadFile, index: number) => {
    if (!file.raw) {
      return false
    }

    if (!file.raw.type.includes('image')) {
      HMessageBox.error('只能上传图片类型的文件')
      return
    }

    if (dataList.value.workSpareMaterials[index].images.length >= 8) {
      HMessageBox.error('最多上传8个')
      return
    }

    dataList.value.workSpareMaterials[index].images.push({
      image: URL.createObjectURL(file.raw),
      file: file.raw,
      id: null,
    })

    setAnnexColumnWidth()
  }

  const onCancel = () => {
    visible.value = false
    emits('update:modelValue', visible.value)
  }

  /**
   * 删除文件
   * @param {number} rowIndex - 操作的表格行的索引
   * @param {number} imgIndex - 文件索引
   */
  const handleDelFile = (rowIndex: number, imgIndex: number) => {
    if (dataList.value.workSpareMaterials[rowIndex].images[imgIndex].id) {
      HMessageBox.error('禁止删除原本附件')
      return
    }
    const imgs = dataList.value.workSpareMaterials[rowIndex].images.splice(imgIndex, 1)
    if (!dataList.value.workSpareMaterials[rowIndex].delImageIds) {
      dataList.value.workSpareMaterials[rowIndex].delImageIds = [imgs[0].id]
    } else {
      dataList.value.workSpareMaterials[rowIndex].delImageIds.push(imgs[0].id)
    }
    setAnnexColumnWidth()
  }

  /**
   * 客户承担输入框输入事件
   * @param {Event} e - input输入元素
   * @param {number} index - 表格操作的行的索引
   */
  const handlecustomerUndertakePriceInput = (e: Event, index: number) => {
    checkNum(e)

    // 防止输入频繁输入会出现三位小数的问题
    dataList.value.workSpareMaterials[index].customerUndertakePrice = Number(
      (e.target as HTMLInputElement).value,
    )

    // 限制金额的最大值为9999999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger(
      (e.target as HTMLInputElement).value,
      10,
    )
  }

  /**
   * 网点承担费用
   * @param {Event} e - Event
   * @param {number} index - 表格操作的行的索引
   */
  const handlenetworkUndertakePriceInput = (e: Event, index: number) => {
    checkNum(e)

    // 防止输入频繁输入会出现三位小数的问题
    dataList.value.workSpareMaterials[index].networkUndertakePrice = Number(
      (e.target as HTMLInputElement).value,
    )

    // 限制金额的最大值为9999999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger(
      (e.target as HTMLInputElement).value,
      10,
    )
  }

  /**
   * 公司承担费用
   * @param {Event} e - Event
   * @param {number} index - 表格操作的行的索引
   */
  const handlePriceInput = (e: Event, index: number) => {
    checkNum(e)

    // 防止输入频繁输入会出现三位小数的问题
    dataList.value.workSpareMaterials[index].price = Number((e.target as HTMLInputElement).value)

    // 限制金额的最大值为9999999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger(
      (e.target as HTMLInputElement).value,
      10,
    )
  }

  // 是否禁用旧件处理方式选择器
  const isDisableCheckStatusSelect = ref(false)

  /**
   * 审核状态更新事件
   */
  const handleSelectCheckStatus = () => {
    let isAllReject = true
    dataList.value.workSpareMaterials.forEach((item) => {
      if (item.status === 2) {
        isAllReject = false
      }
    })

    isDisableCheckStatusSelect.value = false
    if (isAllReject) {
      isDisableCheckStatusSelect.value = true
      dataList.value.oldCopeWay = 1
    }
  }

  const visible = ref(false)
  const formRef = ref<HTMLElement | null>(null)

  /**
   * 获取网点配件类型渲染文本
   * @param val - 配件类型
   */
  const getNetworkSpareTypeRenderTxt = (val: 1 | 3) => {
    const networkSpareType = networkSpareTypeList.find((type) => type.value === val)
    if (networkSpareType) {
      return networkSpareType.name
    }
    return ''
  }

  /**
   * 入库仓库下拉选项搜索事件
   */
  const handleGetWarehouseOptionList = _.debounce((keyword: string) => {
    if (getWarehouseEntryOptionListParam.value.name !== keyword) {
      getWarehouseEntryOptionListParam.value.name = keyword
      getWarehouseEntryOptionList(0)
    }
  }, 600)

  /**
   * 配件编号输入事件
   * @param {string} code - 输入的编号
   * @param {number} sparePartIndex - 配件索引
   */
  const handleSparePartCodeInput = _.debounce(async (code: string, sparePartIndex: number) => {
    const sparePart = dataList.value.workSpareMaterials[sparePartIndex]
    if (!sparePart) {
      return false
    }

    if (code) {
      dataList.value.workSpareMaterials[sparePartIndex].popoverVisible = true
      getGoodListParam.value.keyword = code
      await getGoodList()
    }
  }, 500)

  /**
   * 配件下拉选项点击事件
   * @param sparePartOption - 配件下拉选项
   * @param {number} index - 配件索引
   */
  const handleSparePartOptionClick = async (sparePartOption: GoodItem, index: number) => {
    dataList.value.workSpareMaterials[index].checkSpareModel = sparePartOption.model
    dataList.value.workSpareMaterials[index].specId = ''
    dataList.value.workSpareMaterials[index].checkSpareSpecCode = ''
    dataList.value.workSpareMaterials[index].checkSpareSpec = ''
    dataList.value.workSpareMaterials[index].spareSpecSelect = []
    dataList.value.workSpareMaterials[index].sparePartName = sparePartOption.name
    dataList.value.workSpareMaterials[index].code = sparePartOption.code
    dataList.value.workSpareMaterials[index].spareId = sparePartOption.id
    if (sparePartOption.id) {
      await getPartSpecOptionsFn(sparePartOption.id, index)

      const sparePartSpecOptionList = dataList.value.workSpareMaterials[index].partSpecOptions
      if (sparePartSpecOptionList && sparePartSpecOptionList[0]) {
        handlePartSpecClick(sparePartSpecOptionList[0], index)

        if (dataList.value.workSpareMaterials[index].partSpecOptions[0]) {
          dataList.value.workSpareMaterials[index].specId =
            dataList.value.workSpareMaterials[index].partSpecOptions[0].id
        }
      }
    }
  }

  watch(
    props,
    async (value) => {
      visible.value = value.modelValue

      if (visible.value) {
        await getGoodList()
        await getWarehouseEntryOptionList(0)

        if (value.partsId) {
          await getBeforeCheckOrderSpareDetailInfo(value.partsId)
          await getOrderSpareMaterialList(value.partsId)
        }

        if (
          detailData.value &&
          detailData.value.networkSpareType === 1 &&
          detailData.value.type === 2
        ) {
          await getWarehouse(props.networkId)
          await getReturnWareHouseOptionsFn(1)
          // 如果申请类型是外部配件，网点配件类型是网点仓，那么仓库就要拿网点仓的，并且不能改
          if (detailData.value.networkSpareType === 1 && detailData.value.type === 2) {
            dataList.value.workSpareMaterials = dataList.value.workSpareMaterials.map((item) => {
              item.storeId = warehouse.value.storeId
              return item
            })
          }
        } else {
          await getReturnWareHouseOptionsFn(0)
        }
      }
    },
    { immediate: true, deep: true },
  )
</script>

<style lang="scss" scoped>
  @import './PartCheck.scss';
</style>
